import { Component, OnDestroy, Inject } from '@angular/core'
import { Router } from '@angular/router'
import { FormGroup, FormBuilder, Validators } from '@angular/forms'
import { NzMessageService, NzModalService } from 'ng-zorro-antd'
import { SettingsService } from '@delon/theme'
import { SocialService, ITokenService, DA_SERVICE_TOKEN } from '@delon/auth'

import { StartupService, I18NService } from '@core'
import { LoginService } from './login.service'
import { encryptPassword } from 'app/utils/helpers'
import {
  usernameMaxLength,
  usernameMinLength,
  usernameReg
} from 'app/utils/contraints'
@Component({
  selector: 'passport-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less'],
  providers: [SocialService],
})
export class UserLoginComponent implements OnDestroy {
  errorTips = {}

  constructor(
    fb: FormBuilder,
    modalSrv: NzModalService,
    private router: Router,
    private settingsService: SettingsService,
    @Inject(DA_SERVICE_TOKEN) private tokenService: ITokenService,
    private startupSrv: StartupService,
    private i18n: I18NService,
    public msg: NzMessageService,
    public loginService: LoginService,
  ) {
    this.form = fb.group({
      userName: [null, [
        Validators.required,
        Validators.maxLength(usernameMaxLength),
        Validators.minLength(usernameMinLength),
        Validators.pattern(usernameReg)
      ]],
      password: [null, Validators.required],
      // mobile: [null, [Validators.required, Validators.pattern(/^1\d{10}$/)]],
      veriCode: [null],
      remember: [true],
    })
    this.initErrorTips()
    modalSrv.closeAll()
  }

  // #region fields

  get userName() {
    return this.form.controls.userName
  }
  get password() {
    return this.form.controls.password
  }
  get mobile() {
    return this.form.controls.mobile
  }
  get captcha() {
    return this.form.controls.captcha
  }

  get veriCode() {
    return this.form.controls.veriCode
  }
  get veriCodeURL() {
    return `/servplat-auth/auth/captcha?type=session_login&t=${this.timestamp}`
  }
  timestamp = new Date().getTime()

  form: FormGroup
  error = ''
  type = 0
  isLoading = false

  // #region get captcha

  count = 0
  interval$: any

  initErrorTips() {
    this.errorTips = {
      userName: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('USER.USERNAME') }),
        maxlength: this.trans('VALIDATION.MAX_LENGTH', { length: usernameMaxLength }),
        minlength: this.trans('VALIDATION.MIN_LENGTH', { length: usernameMinLength }),
        pattern: this.trans('VALIDATION.PATTERN.USERNAME')
      },
      password: {
        required: this.trans('VALIDATION.REQUIRED', { name: this.trans('USER.PASSWORD') })
      },
    }
  }

  // #endregion

  switch(ret: any) {
    this.type = ret.index
  }

  getCaptcha() {
    if (this.mobile.invalid) {
      this.mobile.markAsDirty({ onlySelf: true })
      this.mobile.updateValueAndValidity({ onlySelf: true })
      return
    }
    this.count = 59
    this.interval$ = setInterval(() => {
      this.count -= 1
      if (this.count <= 0) clearInterval(this.interval$)
    }, 1000)
  }

  // #endregion

  submit() {
    this.error = ''
    if (this.type === 0) {
      this.userName.markAsDirty()
      this.userName.updateValueAndValidity()
      this.password.markAsDirty()
      this.password.updateValueAndValidity()
      if (this.userName.invalid || this.password.invalid) return
    } else {
      this.mobile.markAsDirty()
      this.mobile.updateValueAndValidity()
      this.captcha.markAsDirty()
      this.captcha.updateValueAndValidity()
      if (this.mobile.invalid || this.captcha.invalid) return
    }
    const reqData = {
      username: this.userName.value,
      password: encryptPassword(this.password.value),
    }
    this.isLoading = true
    this.loginService
      .login(reqData)
      .subscribe(
        resp => {
          this.msg.success(this.trans('GENERAL.NOTIFICATION.LOGIN_SUCCESS'))
          this.tokenService.set(resp)
          this.settingsService.setUser(resp.user)
          // 重新获取 StartupService 内容，我们始终认为应用信息一般都会受当前用户授权范围而影响
          this.startupSrv.load().then(() => {
            // let url = this.tokenService.referrer!.url || '/dashboard'
            let url = '/dashboard'
            if (url.includes('/passport')) url = '/'
            this.router.navigateByUrl(url)
          })
        },
        () => {
          // 暂时除去登录失败的前端报错信息
          // this.msg.error(this.trans('GENERAL.NOTIFICATION.LOGIN_FAIL'))
        },
      )
      .add(() => {
        this.isLoading = false
      })
    // 默认配置中对所有HTTP请求都会强制 [校验](https://ng-alain.com/auth/getting-started) 用户 Token
    // 然一般来说登录请求不需要校验，因此可以在请求URL加上：`/login?_allow_anonymous=true` 表示不触发用户 Token 校验
  }

  refreshVeriCode(): void {
    this.timestamp = new Date().getTime()
  }

  // #endregion
  ngOnDestroy(): void {
    if (this.interval$) clearInterval(this.interval$)
  }

  // 忘记密码
  forgotPassword() {
    this.msg.error(this.trans('ACCOUNT.LOGIN.CONNECT_ADMIN'))
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
